package com.bdy.lm.taximanager.thread;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

import com.bdy.lm.taximanager.app.MyApp;
import com.bdy.lm.taximanager.http.HttpJson;
import com.bdy.lm.taximanager.model.MessagePackaging;
import com.bdy.lm.taximanager.model.QueryCommand;
import com.bdy.lm.taximanager.model.ServerCommandEvent;
import com.bdy.lm.taximanager.model.StandardRoute;
import com.bdy.lm.taximanager.port.TaxiMeterDataAnalysis;
import com.bdy.lm.taximanager.util.JsonUtils;
import com.google.gson.Gson;

import org.json.JSONObject;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/8/14.
 */
public class QueryCommandThread extends Thread {

    private String flag = "查询指令线程";
    private Bundle bundle = new Bundle();
    private Message message = new Message();
    private ServerCommandEvent serverCommandEvent = new ServerCommandEvent();
    private HttpJson httpJson = new HttpJson();
    private MessagePackaging msgPackQuery = new MessagePackaging(103);
    private int messageID, tracePeriod, traceDistance, traceContinueDistance, traceContinueTime, messageSerialNum, traceProperty;
    private int ISUFlag_1; // 一字节，ISU标识，第一字节为10
    private int ISUFlag_company_2; // 一字节，ISU标识，产商编号
    private int ISUFlag_device_3; // 一字节，ISU标识，设备类型
    private int ISUFlag_serialNum_4; // 三字节，ISU标识，序列号
    private QueryCommand queryCommand;

    public void run() {
        while (MyApp.threadRun) {
            JSONObject request = JsonUtils.mapToJsonObject(msgPackQuery.getHeartBitMessagePackageMap());
            //System.out.println("routeNum" + request);
            httpJson.HttpJsonPost(request, MyApp.serverUrl);
            try {
                Thread.sleep(8000);//延时一秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(flag, "运行");
            //"{\"num\":17,\"messageID\":2,\"messageBodayInt\":0,\"flagBitBegin\":126,\"checkCode\":218,\"ISUFlag_device_3\":0,\"flagBitEnd\":126,\"ISUFlag_company_2\":16,\"ISUFlag_1\":16,\"ISUFlag_serialNum_4\":10526880,\"messageBodyString\":\"8120\"}");
            //Log.d(flag, httpJson.getGetJson().toString());
            if (httpJson.getPostJson() != null) {
                String s = httpJson.getPostJson().toString();
                System.out.println("routeNum" + flag + s);
                queryCommand = new Gson().fromJson(s, QueryCommand.class);
                ISUFlag_1 = queryCommand.getISUFlag_1();
                ISUFlag_company_2 = queryCommand.getISUFlag_company_2();
                ISUFlag_device_3 = queryCommand.getISUFlag_device_3();
                ISUFlag_serialNum_4 = queryCommand.getISUFlag_serialNum_4();
                messageID = queryCommand.getMessageID();

                if (true) {//isMine()
                    if (messageID == 1) {
                        messageSerialNum = queryCommand.getMessageSerialNum();
                        //messagePackaging = new MessagePackaging(0x0201);
                        //httpJson.HttpJsonPost(turnToJson.mapToJsonObject(messagePackaging.getResponseQueryLocationMessage(messageSerialNum, (byte) 0)), "url");
                    } else if (messageID == 2) {
                        traceProperty = queryCommand.getTraceProperty();
                        traceContinueDistance = queryCommand.getTraceContinueDistance();
                        traceContinueTime = queryCommand.getTraceContinueTime();
                        tracePeriod = queryCommand.getTracePeriod();
                        traceDistance = queryCommand.getTraceDistance();

                        bundle.putInt("traceProperty", traceProperty);
                        bundle.putInt("tracePeriod", tracePeriod);
                        bundle.putInt("traceContinueTime", traceContinueTime);
                        bundle.putInt("traceDistance", traceDistance);
                        bundle.putInt("traceContinueDistance", traceContinueDistance);
                        message.setData(bundle);
                        message.what = 521;
                        serverCommandEvent.setMessage(message);
                        EventBus.getDefault().post(serverCommandEvent);
                        serverCommandEvent.setMessage(null);
                    } else if (messageID == 108) {//拍照
                        serverCommandEvent.setTakePhotoCommand("takePhoto");
                        EventBus.getDefault().post(serverCommandEvent);
                        httpJson.HttpJsonPost(JsonUtils.mapToJsonObject(new MessagePackaging(104).getIsExecuteMessagePackageMap(queryCommand.getPublishTime())), MyApp.serverUrl);
                        serverCommandEvent.setTakePhotoCommand("haha");
                        System.out.println(flag + "TakePhoto");
                    } else if (messageID == 4) {
                        serverCommandEvent.setRecordVideo("startRecordVideo");
                        EventBus.getDefault().post(this.serverCommandEvent);
                        serverCommandEvent.setRecordVideo(null);
                    } else if (messageID == 5) {
                        serverCommandEvent.setRecordVideo("stopRecordVideo");
                        EventBus.getDefault().post(this.serverCommandEvent);
                        serverCommandEvent.setRecordVideo(null);
                    } else if (messageID == 6) {
                        serverCommandEvent.setRecordVideo("startRecordVideoTime");
                        serverCommandEvent.setVideoTime(12);
                        EventBus.getDefault().post(this.serverCommandEvent);
                        serverCommandEvent.setVideoTime(0);
                        serverCommandEvent.setRecordVideo(null);
                    } else if (messageID == 7) {
                        serverCommandEvent.setRecorder("startRecorder");
                        EventBus.getDefault().post(this.serverCommandEvent);
                        serverCommandEvent.setRecorder(null);
                    } else if (messageID == 8) {
                        serverCommandEvent.setRecorder("stopRecorder");
                        EventBus.getDefault().post(this.serverCommandEvent);
                        serverCommandEvent.setRecorder(null);
                    } else if (messageID == 109) {//接收消息
                        serverCommandEvent.setReceivedMessage(queryCommand.getMessage());
                        EventBus.getDefault().post(serverCommandEvent);
                        System.out.println(flag + queryCommand.getMessage()+"||"+queryCommand.getPublishTime());
                        httpJson.HttpJsonPost(JsonUtils.mapToJsonObject(new MessagePackaging(104).getIsExecuteMessagePackageMap(queryCommand.getPublishTime())), MyApp.serverUrl);
                        serverCommandEvent.setReceivedMessage("haha");
                    } else if (messageID == 10) {
                        System.out.println("msg");
                    } else if (messageID == 117) {
//                        final String routeNum = queryCommand.getMessage();
//                        System.out.println("routeNum" + routeNum);
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                boolean flag = true;
//                                HttpJson hj = new HttpJson();
//                                while(flag) {
//                                    JSONObject con = JsonUtils.mapToJsonObject(new MessagePackaging(113).getQueryStandRouteMap(routeNum));
//                                    System.out.println("content" + con.toString());
//                                    hj.HttpJsonPost(con, MyApp.serverUrl);
//                                    if (hj.getPostJson() == null) {
//                                        System.out.println("standardRoute为空"+hj.getPostJson());
//                                        hj.HttpJsonPost(con, MyApp.serverUrl);
//                                        try {
//                                            Thread.sleep(1000);
//                                        } catch (InterruptedException e) {
//                                            e.printStackTrace();
//                                        }
//                                    } else {
//                                        try {
//                                            JSONObject sr = hj.getPostJson();
//                                            String sRoute = sr.getJSONObject("standardRoute").toString();
//                                            System.out.println("standardRoute" + sRoute);
//                                            StandardRoute sR = new Gson().fromJson(sRoute, StandardRoute.class);
//
//                                            serverCommandEvent.setReceivedMessage("收到校准路线！");
//                                            EventBus.getDefault().post(serverCommandEvent);
//                                            serverCommandEvent.setReceivedMessage(null);
//
//                                            putIn(sRoute, sR);
//                                            VerifyAdjustThread.getInstance().receiveVerifyNotify();
//                                        } catch (JSONException e) {
//                                            e.printStackTrace();
//                                        }
//                                        hj.HttpJsonPost(JsonUtils.mapToJsonObject(new MessagePackaging(104).getIsExecuteMessagePackageMap(queryCommand.getPublishTime())), MyApp.serverUrl);
//                                        flag = false;
//                                    }
//                                }
//                            }
//                        }).start();
                        //VerifyAdjustThread.getInstance().receiveVerifyNotify();
                        //new HttpJson().HttpJsonPost(JsonUtils.mapToJsonObject(new MessagePackaging(104).getIsExecuteMessagePackageMap(queryCommand.getPublishTime())), MyApp.serverUrl);

                    } else if(messageID == 115) {
                        System.out.println("收到查询参数指令");
                        TaxiMeterDataAnalysis.newInstance().getTaximeterParameter(TaxiMeterDataAnalysis.SERVER);
                        httpJson.HttpJsonPost(JsonUtils.mapToJsonObject(new MessagePackaging(104).getIsExecuteMessagePackageMap(queryCommand.getPublishTime())), MyApp.serverUrl);
                    }
                }
            }
            //serverCommandEvent.setReceivedMessage("信息已经收到了");
            //EventBus.getDefault().post(serverCommandEvent);
        }
    }
    boolean isMine() {
        if (ISUFlag_1 == MyApp.ISUFlag_1 && ISUFlag_company_2 == MyApp.ISUFlag_company_2 && ISUFlag_device_3 == MyApp.ISUFlag_device_3 && ISUFlag_serialNum_4 == MyApp.ISUFlag_serialNum_4) {
            return true;
        } else {
            return false;
        }
    }

    private void putIn(String s, StandardRoute sR) {
        Log.d("standardRouteNum   4", "开始存储");
        SharedPreferences sp = MyApp.context.getSharedPreferences(VerifyAdjustThread.STANDARD_ROUTE_SP_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
//        String standardRouteNum = Integer.toString(sR.getNum());
//        if (sp.contains(VerifyAdjustThread.STANDARD_ROUTE_NUMS)) {
//            standardRouteNum = sp.getString(VerifyAdjustThread.STANDARD_ROUTE_NUMS, null) + VerifyAdjustThread.NUM_SPILT + standardRouteNum;
//        }
//        editor.putString(VerifyAdjustThread.STANDARD_ROUTE_NUMS, standardRouteNum);
        editor.putString(Integer.toString(sR.getNum()), s);
        editor.commit();
        Log.d("standardRouteNum   5", "存储成功");
/*        int num = s.getNum();
        editor.putInt("num", s.getNum());
        editor.putString("Alongitude"+num, Double.toString(s.getAlongitude()));
        editor.putString("Alatitude"+num, Double.toString(s.getAlatitude()));
        editor.putString("Aaltitude"+num, Double.toString(s.getAaltitude()));
        editor.putString("Aradius"+num, Double.toString(s.getAradius()));
        editor.putString("Blongtitde"+num, Double.toString(s.getBlongtitde()));
        editor.putString("Blatitude"+num, Double.toString(s.getBlatitude()));
        editor.putString("Baltitude"+num, Double.toString(s.getBaltitude()));
        editor.putString("Bradius"+num, Double.toString(s.getBradius()));
        editor.putString("Smeasure"+num, Double.toString(s.getSmeasure()));
        editor.putString("Standard"+num, Double.toString(s.getStandard()));
        editor.commit();*/
    }
}
